package com.sdkx.wear_os.ui.activity

import android.content.Intent
import android.view.KeyEvent
import androidx.recyclerview.widget.LinearLayoutManager
import com.sdkx.wear_os.R
import com.sdkx.wear_os.adapter.MainAdapter
import com.sdkx.wear_os.base.BaseActivity
import com.sdkx.wear_os.base.BaseViewModel
import com.sdkx.wear_os.bean.MineBean
import com.sdkx.wear_os.databinding.ActivityMainBinding
import com.sdkx.wear_os.utils.ToastLogUtils
import com.sdkx.wear_os.utils.getAppViewModel
import com.sdkx.wear_os.viewmodel.AppViewModel
import kotlin.system.exitProcess

/**
 * 主程序
 */
class MainActivity : BaseActivity<BaseViewModel, ActivityMainBinding>() {

    //全局viewModel
    private val appViewModel: AppViewModel by lazy { getAppViewModel() }

    //第一次点击
    private var firstTime: Long = 0

    private var mainAdapter = MainAdapter()

    override fun initLayout() = R.layout.activity_main

    override fun initView() {
        isDarkFont = false
        mViewModel.swipe = mDataBinding.swipe
    }

    override fun initData() {
        val mainData = mutableListOf<MineBean>()
        mainData.add(MineBean("11111111", ""))
        mainData.add(MineBean("22222222", ""))
        mainData.add(MineBean("33333333", ""))
        mainAdapter.items = mainData
        mDataBinding.recyclerview.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = mainAdapter
        }
    }

    override fun initListener() {
        //刷新
        mDataBinding.swipe.setOnRefreshListener {
            mDataBinding.swipe.isRefreshing = false
        }
        //点击列表
        mainAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, DetailActivity::class.java)
            startActivity(intent)
        }
    }

    /**
     * 返回按键
     */
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            val secondTime = System.currentTimeMillis()
            if (secondTime - firstTime > 2000) {
                ToastLogUtils.toastUtil("再按一次退出程序")
                firstTime = secondTime
            } else {
                finish()
                exitProcess(0)
            }
            return false
        }
        return super.dispatchKeyEvent(event)
    }
}